/**
 * Toast通知组件
 * 显示全局通知消息
 */
import React, { useState, useEffect } from 'react';
import { Snackbar, Alert, AlertColor } from '@mui/material';
import { registerToastListener } from '../../utils/ui/toast.ts';

interface ToastMessage {
  id: number;
  message: string;
  type: AlertColor;
}

/**
 * Toast通知组件
 * 接收并显示从toast工具发送的通知
 */
const Toast: React.FC = () => {
  const [open, setOpen] = useState(false);
  const [messageQueue, setMessageQueue] = useState<ToastMessage[]>([]);
  const [currentMessage, setCurrentMessage] = useState<ToastMessage | null>(null);
  
  // 处理关闭事件
  const handleClose = (_: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === 'clickaway') {
      return;
    }
    setOpen(false);
  };
  
  // 处理退出动画完成后的操作
  const handleExited = () => {
    // 处理下一条消息
    processQueue();
  };
  
  // 处理消息队列
  const processQueue = () => {
    if (messageQueue.length > 0) {
      // 取队列中第一条消息
      const message = messageQueue[0];
      setCurrentMessage(message);
      setMessageQueue(prev => prev.slice(1));
      setOpen(true);
    } else {
      setCurrentMessage(null);
    }
  };
  
  // 监听全局Toast事件
  useEffect(() => {
    const unregister = registerToastListener((message, type) => {
      const newMessage: ToastMessage = {
        id: Date.now(),
        message,
        type: type as AlertColor
      };
      
      setMessageQueue(prev => [...prev, newMessage]);
      
      // 如果当前没有显示消息，立即处理队列
      if (!currentMessage) {
        processQueue();
      }
    });
    
    return () => {
      unregister();
    };
  }, [currentMessage]);
  
  return (
    <Snackbar
      key={currentMessage ? currentMessage.id : undefined}
      open={open}
      autoHideDuration={3000}
      onClose={handleClose}
      TransitionProps={{ onExited: handleExited }}
      anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
    >
      <Alert
        onClose={handleClose}
        severity={currentMessage?.type || 'info'}
        variant="filled"
        sx={{ width: '100%' }}
      >
        {currentMessage?.message || ''}
      </Alert>
    </Snackbar>
  );
};

export default Toast; 